package com.lujianfei.powerinput.ui.template.presenter;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;

import com.lujianfei.powerinput.database.NoteItemFieldModel;
import com.lujianfei.powerinput.database.TemplateFieldModel;
import com.lujianfei.powerinput.database.TemplateModel;
import com.lujianfei.powerinput.ui.noteList.NoteListEditActivity;
import com.lujianfei.powerinput.ui.template.TemplateActivity;
import com.lujianfei.powerinput.ui.template.TemplateAddActivity;
import com.lujianfei.powerinput.ui.template.base.TemplateContract;
import com.lujianfei.powerinput.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AlertDialog;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.BiConsumer;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class TemplatePresenter implements TemplateContract.Presenter {
    private final static String TAG = "TemplatePresenter";
    private final TemplateContract.View view;
    private List<TemplateModel> templateModels;
    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    public TemplatePresenter(TemplateContract.View view) {
        this.view = view;
    }

    @Override
    public void onTitleRightImageClick() {
        view.currentActivity().startActivity(new Intent(view.currentActivity(),TemplateAddActivity.class));
    }

    @Override
    public void initData() {
        Observable<List<String>> observable = Observable.create(new ObservableOnSubscribe<List<String>>() {
            @Override
            public void subscribe(final ObservableEmitter<List<String>> emitter) throws Exception {
                try {
                    templateModels = TemplateModel.listAll(TemplateModel.class);
                    Observable.fromIterable(templateModels).map(new Function<TemplateModel, String>() {
                        @Override
                        public String apply(TemplateModel templateModel) {
                            return templateModel.getName();
                        }
                    }).toList().subscribe(new BiConsumer<List<String>, Throwable>() {
                        @Override
                        public void accept(List<String> strings, Throwable throwable) throws Exception {
                            emitter.onNext(strings);
                        }
                    });
                }catch (Exception e){
                    Log.e(TAG,""+e);
                }
            }
        });
        DisposableObserver<List<String>> disposableObserver = new DisposableObserver<List<String>>() {
            @Override
            public void onNext(List<String> result) {
                view.updateList(result);
                if(result.isEmpty()){
                    view.showEmptyView();
                }else{
                    view.hideEmptyView();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(disposableObserver);
        compositeDisposable.add(disposableObserver);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view2, int i, long l) {
        String operType = view.getOperType();
        if (TemplateActivity.TYPE_SELECT.equalsIgnoreCase(operType)){
            TemplateModel templateModel = templateModels.get(i);
            Intent intent = new Intent();
            intent.putExtra("data",templateModel);
            view.currentActivity().setResult(Activity.RESULT_OK,intent);
            view.currentActivity().finish();
        }else{
            TemplateModel templateModel = templateModels.get(i);
            Intent intent = new Intent(view.currentActivity(), TemplateAddActivity.class);
            intent.putExtra("data",templateModel);
            view.currentActivity().startActivity(intent);
        }
    }

    @Override
    public void onItemLongClick(final AdapterView<?> adapterView, final View view2, final int index, final long l) {
        final TemplateModel templateModel = templateModels.get(index);
        final String[] items = new String[]{"删除","编辑","取消"};
        new AlertDialog.Builder(view.currentActivity()).setTitle("操作")
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        String item = items[i];
                        if ("删除".equalsIgnoreCase(item)){
                            new AlertDialog.Builder(view.currentActivity()).setTitle("提示")
                                    .setMessage("确定要删除"+templateModel.getName()+"?")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            dialogInterface.dismiss();
                                            TemplateFieldModel.deleteAll(TemplateFieldModel.class,"templateId=?",""+templateModel.getId());
                                            templateModel.delete();
                                            initData();
                                            ToastUtils.show("删除成功");
                                        }
                                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();
                                }
                            }).show();
                        }
                        else if ("编辑".equalsIgnoreCase(item)){
                            onItemClick(adapterView,view2,index,l);
                        }
                    }
                }).show();
    }

    @Override
    public void onDestroy() {
        compositeDisposable.clear();
    }
}
